﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Hanselman.Portable;
using ig.app.Services.ig.app.Services;
using Xamarin.Forms;

namespace ig.app.ViewModels
{



    class SettingViewModel : BaseViewModel
    {
        private bool _isSearchingUrls = false;
        private Command _scan;
        private string _serverUrl;
        private Command _connect;
        private Command _scanLocal;
        private double _scanLocalstep;
        private string _listSelectValue;
        private bool _isVisibleSearchedUrls;
        private Command _searchedUrlsCommand;
        private string[] _searchedUrls;

        public bool IsSearchingUrls
        {
            get { return _isSearchingUrls; }
            set { SetProperty(ref _isSearchingUrls, value); }
        }

        //public readonly ObservableCollection<string> SearchedUrls = new ObservableCollection<string>();
        public string[] SearchedUrls
        {
            get { return _searchedUrls; }
            set { SetProperty(ref _searchedUrls, value); }
        }

        public Command Scan
        {
            get
            {
                return _scan ?? (_scan = new Command(() =>
                       {

                           ScanLocalstep = 0.3;
                       }));
            }

        }

        public string ServerUrl
        {
            get { return _serverUrl; }
            set { SetProperty(ref _serverUrl, value); }
        }

        public Command Connect
        {
            get
            {
                return _connect ?? (_connect = new Command(() =>
                       {
                           ScanLocalstep = 0.8;
                       }));
            }
        }

        public double ScanLocalstep
        {
            get { return _scanLocalstep; }
            set { SetProperty(ref _scanLocalstep, value); }
        }

        public string ListSelectValue
        {
            get { return _listSelectValue; }
            set
            {
                SetProperty(ref _listSelectValue, value);
                ServerUrl = value;
                IsVisibleSearchedUrls = false;
            }
        }

        public bool IsVisibleSearchedUrls
        {
            get { return _isVisibleSearchedUrls; }
            set { SetProperty(ref _isVisibleSearchedUrls, value); }
        }

        public Command SearchedUrlsCommand
        {
            get
            {
                return _searchedUrlsCommand ?? (_searchedUrlsCommand = new Command<string>(su =>
                           {
                               if (su != null)
                               {
                                   ServerUrl = su;
                               }
                               IsVisibleSearchedUrls = false;
                           }));
            }
        }

        private async Task<string> UrlCanGet(string url)
        {
            using (var hc = new HttpClient())
            {
                try
                {
                    var r = hc?.GetAsync(url).Result;
                    if (r?.IsSuccessStatusCode == true)
                    {

                    }
                    return url;
                    //SearchedUrls.Add(s);
                }
                catch (Exception ex)
                {
                    // ignored
                }
                finally
                {
                    ist += 1;
                    ScanLocalstep = 1d * ist / ipcount;
                }
                return "";
            }
        }

        int ipcount = 1;
        int ist = 0;
        public Command ScanLocal
        {
            get
            {
                return _scanLocal ?? (_scanLocal = new Command(async () =>
                {
                    if (IsSearchingUrls) return;
                    ScanLocalstep = 0;
                    ist = 0;
                    IsSearchingUrls = true;
                    //IsVisibleSearchedUrls = true;
                    SearchedUrls = new string[0];
                    //SearchedUrls.Clear();




                    //var urls2 =await DependencyService.Get<IIPAddressManager>().GetLocalServer();
                    var ipaddress = (await DependencyService.Get<IIPAddressManager>().GetIPAddress()).Where(w => !w.StartsWith("16")).ToArray();

                    var urls = new List<string>();
                    foreach (var ip in ipaddress)
                    {
                        var ipmask = ip.Substring(0, ip.LastIndexOf('.'));
                        for (var i = 1; i < 255; i++)
                        {
                            var url = "http://" + ipmask + "." + i + ":5000";
                            urls.Add(url);
                        }
                    }
                    ipcount = urls.Count;
                    //var urls2 = new string[urls.Count];

                    // Create a query. 
                    IEnumerable<Task<string>> downloadTasksQuery = from url in urls select UrlCanGet(url);//urls.Select(UrlCanGet));
                    // Use ToArray to execute the query and start the download tasks.
                    Task<string>[] downloadTasks = downloadTasksQuery.ToArray();
                    var urls2 = await Task.WhenAll(downloadTasks);

                    //while (true)
                    //{
                    //    await Task.Delay(1000);
                    //    if (ist >= ipcount) break;
                    //}


                    var u2 = urls2.Where(w => !string.IsNullOrWhiteSpace(w)).ToArray();
                    IsVisibleSearchedUrls = u2.Length > 0;
                    SearchedUrls = u2;


                    IsSearchingUrls = false;

                }));
            }
        }
    }
}
